<template>
	<view class="page">
		<!-- 待审批数量统计 -->
		<view class="stats-container">
			<view class="stat-item" @click="navigateToApproval('pending')">
				<text class="stat-num">{{ statistics.pending }}</text>
				<text class="stat-label">待审批任务</text>
			</view>
		</view>
		
		<!-- 审批类型选择 -->
		<view class="approval-types-section">
			<view class="section-title">审批类型</view>
			<view class="approval-types-grid">
				<view 
					class="approval-type-item" 
					v-for="type in availableApprovalTypes" 
					:key="type.key"
					@click="navigateToApprovalType(type.key)"
					:class="{ 'disabled': !type.enabled }"
				>
					<view class="type-icon" :class="'icon-' + type.key">
						<uni-icons :type="type.icon" size="32" :color="type.enabled ? type.color : '#ccc'"></uni-icons>
					</view>
					<text class="type-name">{{ type.name }}</text>
					<text class="type-count" v-if="type.count > 0">{{ type.count }}</text>
					
				</view>
			</view>
		</view>
		
		<!-- 待审批流程列表 -->
		<view class="approval-section">
			<view class="section-header">
				<text class="section-title">待我审批</text>
				<text class="more" @click="navigateToApproval('pending')">
					更多
					<uni-icons type="right" size="14" color="#999"></uni-icons>
				</text>
			</view>
			
			<view class="approval-list" v-if="approvalList.length > 0">
				<view 
					class="approval-item" 
					v-for="item in approvalList" 
					:key="item.id"
				>
					<view class="item-header">
						<view class="type-tag" :class="'type-' + item.type">
							{{ item.typeName }}
						</view>
						<text class="time">{{ item.createTime }}</text>
					</view>
					<view class="item-content" @click="navigateToDetail(item.id)">
						<text class="title">{{ item.title }}</text>
						<text class="desc">申请人：{{ item.applicant }}</text>
					</view>
					<view class="item-footer">
						<text class="amount" v-if="item.amount">￥{{ item.amount }}</text>
						<view class="status pending">待审批</view>
					</view>
					
					<!-- 操作按钮 -->
					<view class="action-buttons" v-if="item && item.id">
						<button 
							class="action-btn approve-btn" 
							@click.stop="handleApprove(item)"
							:disabled="item.processing"
						>
							{{ item.processing ? '处理中...' : '通过' }}
						</button>
						<button 
							class="action-btn reject-btn" 
							@click.stop="handleReject(item)"
							:disabled="item.processing"
						>
							{{ item.processing ? '处理中...' : '拒绝' }}
						</button>
					</view>
				</view>
			</view>
			
			<view class="empty" v-else>
				<uni-icons type="info" size="60" color="#ccc"></uni-icons>
				<text class="empty-text">暂无待审批流程</text>
			</view>
		</view>
	</view>
</template>

<script>
import { getUserInfo, isLoggedIn } from '@/utils/auth.js'
import { queryUserFlow } from '@/api/approval.js'

export default {
	data() {
		return {
			userInfo: {},
			statistics: {
				pending: 0
			},
			approvalList: [],
			loading: false,
			// 审批类型配置
			approvalTypes: [
				{
					key: 'new',
					name: '新增审批',
					icon: 'compose',
					color: '#ff6b6b'
				},
				{
					key: 'complaint',
					name: '投诉审批',
					icon: 'chatboxes',
					color: '#ff6b6b'
				},
				{
					key: 'return',
					name: '退货审批',
					icon: 'undo',
					color: '#ffa502'
				},
				{
					key: 'order',
					name: '订单审批',
					icon: 'list',
					color: '#4ecb73'
				}
			]
		}
	},
	computed: {
		// 获取所有可用的审批类型（移除权限限制）
		availableApprovalTypes() {
			console.log('获取审批类型 - 用户信息:', this.userInfo)
			
			return this.approvalTypes.map(type => {
				console.log(`处理审批类型: ${type.name} (${type.key})`)
				
				// 计算该类型的待审批数量
				const count = this.getApprovalCountByType(type.key)
				
				return {
					...type,
					enabled: true, // 所有审批类型都启用
					count: count
				}
			})
		}
	},
	onLoad() {
		// 允许无 token 访问首页：若未登录则展示默认信息
		if (!isLoggedIn()) {
			this.userInfo = { realName: '未登录', department: '', position: '' }
		} else {
			// 加载用户信息
			this.loadUserInfo()
			// 加载待审批列表
			this.loadApprovalList()
		}
	},
	onShow() {
		// 每次显示页面时刷新数据
		if (isLoggedIn()) {
			this.loadApprovalList()
		}
	},
	methods: {
		// 加载用户信息
		loadUserInfo() {
			this.userInfo = getUserInfo() || {}
			
			// 调试信息：打印原始用户信息
			console.log('原始用户信息:', this.userInfo)
			console.log('用户角色:', this.userInfo.roles)
			
			// 将角色名称映射为角色代码
			if (this.userInfo.roles && this.userInfo.roles.length > 0) {
				const originalRoles = [...this.userInfo.roles]
				this.userInfo.roles = this.userInfo.roles.map(roleName => {
					const roleMapping = {
						'系统管理员': 'ADMIN',
						'办事处商务': 'OFFICE_BUSINESS',
						'地区经理': 'REGIONAL_MANAGER',
						'大区经理': 'REGIONAL_DIRECTOR',
						'市场部经理': 'MARKETING_MANAGER',
						'物流总监': 'LOGISTICS_DIRECTOR',
						'销售总监': 'SALES_DIRECTOR',
						'公司商务': 'COMPANY_BUSINESS',
						'信用控制组': 'CREDIT_CONTROL_GROUP',
						'销售人员': 'SALES_PERSON',
						'投诉主管': 'COMPLAINT_SUPERVISOR',
						'商务经理': 'BUSINESS_MANAGER'
					}
					const mappedRole = roleMapping[roleName] || roleName
					console.log(`角色映射: ${roleName} -> ${mappedRole}`)
					return mappedRole
				})
				
				// 调试信息：打印映射后的角色
				console.log('原始角色:', originalRoles)
				console.log('映射后角色:', this.userInfo.roles)
			} else {
				console.log('用户没有角色信息或角色为空')
			}
		},
		
		// 加载待审批列表
		async loadApprovalList() {
			this.loading = true
			
			try {
				// 获取待审批任务列表
				const approvalRes = await queryUserFlow(this.userInfo.username || 'admin')
				
				console.log('API 响应:', approvalRes)
				
				// 处理待审批列表数据
				if (approvalRes.code === 200) {
					console.log('API 调用成功，响应数据:', approvalRes)
					
					if (approvalRes.data && Array.isArray(approvalRes.data)) {
						console.log('原始数据:', approvalRes.data)
						
						this.approvalList = approvalRes.data.map(item => ({
							id: item.id || item.taskId, // 使用taskId作为id
							taskId: item.taskId, // 保存taskId
							type: this.getApprovalTypeByProcDefId(item.processDefinitionId),
							typeName: this.getApprovalTypeNameByProcDefId(item.processDefinitionId),
							title: item.taskName || '待审批任务',
							applicant: item.applicant || '系统用户',
							amount: item.amount || '',
							createTime: this.formatTime(item.createTime),
							status: 'pending'
						}))
						
						console.log('处理后的审批列表:', this.approvalList)
						
						// 直接使用待审批任务列表的长度作为待审批数量
						this.statistics = {
							pending: this.approvalList.length
						}
					} else {
						console.log('API 返回的 data 为空或不是数组')
						this.approvalList = []
						this.statistics = { pending: 0 }
					}
				} else {
					console.log('API 调用失败，code:', approvalRes.code, 'message:', approvalRes.message)
					this.approvalList = []
					this.statistics = { pending: 0 }
				}
				
			} catch (error) {
				console.error('加载待审批列表失败:', error)
				// 出错时使用空数据
				this.approvalList = []
				this.statistics = { pending: 0 }
			} finally {
				this.loading = false
			}
		},
		
		// 根据流程定义ID获取审批类型
		getApprovalTypeByProcDefId(processDefinitionId) {
			if (!processDefinitionId) return 'other'
			
			// 从流程定义ID中提取流程key（格式：complaintProcess:1:2508）
			const processKey = processDefinitionId.split(':')[0]
			
			switch (processKey) {
				case 'complaintProcess':
					return 'complaint'
				case 'orderProcess':
					return 'order'
				case 'customerProcess':
				case 'existingCustomerProcess':
				case 'distributorCustomerProcess':
					return 'new' // 客户相关流程都归类为新增审批
				case 'newCustomerProcess':
				case 'newCustomerApprovalProcess':
					return 'new' // 新增用户流程
				case 'returnProcess':
					return 'return'
				default:
					return 'other'
			}
		},
		
		// 根据流程定义ID获取审批类型名称
		getApprovalTypeNameByProcDefId(processDefinitionId) {
			if (!processDefinitionId) return '其他'
			
			// 从流程定义ID中提取流程key
			const processKey = processDefinitionId.split(':')[0]
			
			switch (processKey) {
				case 'complaintProcess':
					return '投诉审批'
				case 'orderProcess':
					return '订单审批'
				case 'customerProcess':
				case 'existingCustomerProcess':
				case 'distributorCustomerProcess':
					return '新增审批' // 客户相关流程都归类为新增审批
				case 'newCustomerProcess':
				case 'newCustomerApprovalProcess':
					return '新增审批' // 新增用户流程
				case 'returnProcess':
					return '退货审批'
				default:
					return '其他审批'
			}
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}`
		},
		
		
		
		// 跳转到审批列表页
		navigateToApproval(status) {
			uni.navigateTo({
				url: `/pages/approval/list?status=${status}`
			})
		},
		
		// 跳转到审批详情页
		navigateToDetail(id) {
			// 找到对应的任务项，获取taskId
			const taskItem = this.approvalList.find(item => item.id === id)
			if (taskItem && taskItem.taskId) {
				console.log('当前用户在task表中的taskId:', taskItem.taskId)
				console.log('任务详情:', {
					id: taskItem.id,
					taskId: taskItem.taskId,
					title: taskItem.title,
					applicant: taskItem.applicant
				})
			} else {
				console.warn('未找到对应的taskId，id:', id)
			}
			
			uni.navigateTo({
				url: `/pages/approval/detail?id=${id}&taskId=${taskItem?.taskId || ''}`
			})
		},
		
		// 根据审批类型获取待审批数量
		getApprovalCountByType(type) {
			if (!this.approvalList || this.approvalList.length === 0) {
				return 0
			}
			
			// 根据类型过滤待审批列表
			return this.approvalList.filter(item => {
				switch (type) {
					case 'new':
						return item.type === 'new' || item.title.includes('新增') || item.title.includes('客户')
					case 'complaint':
						return item.type === 'complaint' || item.title.includes('投诉')
					case 'return':
						return item.type === 'return' || item.title.includes('退货')
					case 'order':
						return item.type === 'order' || item.title.includes('订单')
					default:
						return false
				}
			}).length
		},
		
		// 跳转到指定审批类型页面
		navigateToApprovalType(type) {
			// 从可用审批类型中查找
			const typeConfig = this.availableApprovalTypes.find(t => t.key === type)
			if (!typeConfig) {
				uni.showToast({
					title: '审批类型不存在',
					icon: 'none'
				})
				return
			}
			
			// 跳转到对应的审批列表页面
			uni.navigateTo({
				url: `/pages/approval/list?type=${type}&name=${encodeURIComponent(typeConfig.name)}`
			})
		},
		
		// 处理审批通过
		async handleApprove(item) {
			// 调试信息
			console.log('handleApprove 被调用，item:', item)
			console.log('当前 approvalList:', this.approvalList)
			console.log('approvalList 长度:', this.approvalList.length)
			
			// 检查item是否存在
			if (!item) {
				console.error('审批项目不存在')
				uni.showToast({
					title: '审批项目不存在',
					icon: 'none'
				})
				return
			}
			
			try {
				// 设置处理状态
				item.processing = true
				
				uni.showLoading({ title: '审批中...' })
				
				// 调用审批通过接口
				const result = await this.approveProcess(item.taskId || item.id)
				
				if (result.code === 200) {
					uni.hideLoading()
					uni.showToast({
						title: '审批通过成功',
						icon: 'success'
					})
					
					// 更新本地状态
					item.status = 'approved'
					item.processing = false
					
					// 刷新列表
					this.loadApprovalList()
				} else {
					uni.hideLoading()
					uni.showToast({
						title: result.message || '审批失败',
						icon: 'none'
					})
					item.processing = false
				}
			} catch (error) {
				uni.hideLoading()
				console.error('审批通过失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
				// 安全地设置processing状态
				if (item) {
					item.processing = false
				}
			}
		},
		
		// 处理审批拒绝
		async handleReject(item) {
			// 检查item是否存在
			if (!item) {
				console.error('审批项目不存在')
				uni.showToast({
					title: '审批项目不存在',
					icon: 'none'
				})
				return
			}
			
			try {
				// 显示拒绝原因输入框
				uni.showModal({
					title: '拒绝原因',
					editable: true,
					placeholderText: '请输入拒绝原因',
					success: async (res) => {
						if (res.confirm && res.content) {
							// 设置处理状态
							item.processing = true
							
							uni.showLoading({ title: '审批中...' })
							
							// 调用审批拒绝接口
							const result = await this.rejectProcess(item.taskId || item.id, res.content)
							
							if (result.code === 200) {
								uni.hideLoading()
								uni.showToast({
									title: '审批拒绝成功',
									icon: 'success'
								})
								
								// 更新本地状态
								item.status = 'rejected'
								item.processing = false
								
								// 刷新列表
								this.loadApprovalList()
							} else {
								uni.hideLoading()
								uni.showToast({
									title: result.message || '审批失败',
									icon: 'none'
								})
								item.processing = false
							}
						}
					}
				})
			} catch (error) {
				uni.hideLoading()
				console.error('审批拒绝失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
				// 安全地设置processing状态
				if (item) {
					item.processing = false
				}
			}
		},
		
		// 审批通过接口调用
		async approveProcess(taskId) {
			const { approveProcess } = await import('@/api/approval.js')
			return await approveProcess(taskId)
		},
		
		// 审批拒绝接口调用
		async rejectProcess(taskId, reason) {
			const { rejectProcess } = await import('@/api/approval.js')
			return await rejectProcess(taskId, reason)
		}
		
	}
}
</script>

<style scoped>
.page {
	min-height: 100vh;
	background: #f5f7fa;
}

/* 统计卡片 */
.stats-container {
	display: flex;
	background: #ffffff;
	margin: 20rpx 30rpx;
	border-radius: 16rpx;
	padding: 40rpx 0;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	justify-content: center;
}

.stat-item {
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	cursor: pointer;
	transition: transform 0.2s;
}

.stat-item:active {
	transform: scale(0.98);
}

.stat-num {
	font-size: 44rpx;
	font-weight: bold;
	color: #667eea;
	margin-bottom: 10rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #999999;
}

/* 审批类型选择 */
.approval-types-section {
	padding: 0 30rpx;
	margin-top: 30rpx;
}

.approval-types-section .section-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 25rpx;
}

.approval-types-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
	background: #ffffff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.approval-type-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30rpx 20rpx;
	border-radius: 12rpx;
	background: #f8f9fa;
	transition: all 0.3s ease;
	position: relative;
}

.approval-type-item:active {
	transform: scale(0.98);
	background: #e9ecef;
}

.approval-type-item.disabled {
	opacity: 0.5;
	background: #f5f5f5;
}

.approval-type-item.disabled:active {
	transform: none;
	background: #f5f5f5;
}

.type-icon {
	margin-bottom: 15rpx;
}

.type-name {
	font-size: 26rpx;
	color: #333333;
	font-weight: 500;
	margin-bottom: 8rpx;
}

.type-count {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	background: #ff4757;
	color: #ffffff;
	font-size: 20rpx;
	padding: 4rpx 8rpx;
	border-radius: 10rpx;
	min-width: 24rpx;
	text-align: center;
	line-height: 1;
}


/* 审批列表 */
.approval-section {
	padding: 0 30rpx;
	margin-top: 30rpx;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 25rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
}

.more {
	font-size: 26rpx;
	color: #999999;
	display: flex;
	align-items: center;
}

.approval-list {
	background: #ffffff;
	border-radius: 16rpx;
	overflow: hidden;
}

.approval-item {
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.approval-item:last-child {
	border-bottom: none;
}

.approval-item:active {
	background: #f5f7fa;
}

.item-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15rpx;
}

.type-tag {
	padding: 8rpx 16rpx;
	border-radius: 6rpx;
	font-size: 22rpx;
	color: #ffffff;
}

.type-new {
	background: #667eea;
}

.type-complaint {
	background: #ff6b6b;
}

.type-return {
	background: #ffa502;
}

.type-order {
	background: #4ecb73;
}

.type-other {
	background: #999999;
}

.time {
	font-size: 24rpx;
	color: #999999;
}

.item-content {
	margin-bottom: 15rpx;
}

.title {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 10rpx;
}

.desc {
	font-size: 24rpx;
	color: #666666;
	display: block;
}

.item-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.amount {
	font-size: 30rpx;
	font-weight: bold;
	color: #ff6b6b;
}

.status {
	padding: 6rpx 20rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
}

.status.pending {
	background: #fff3e0;
	color: #ff9800;
}

/* 空状态 */
.empty {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 80rpx 0;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.empty-text {
	font-size: 28rpx;
	color: #999999;
	margin-top: 20rpx;
}

/* 操作按钮样式 */
.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1rpx solid #f0f0f0;
}

.action-btn {
	flex: 1;
	padding: 20rpx 30rpx;
	border-radius: 12rpx;
	font-size: 26rpx;
	font-weight: bold;
	border: none;
	transition: all 0.3s ease;
	position: relative;
	overflow: hidden;
}

.action-btn:disabled {
	opacity: 0.6;
	transform: none !important;
}

.action-btn:not(:disabled):active {
	transform: scale(0.95);
}

.approve-btn {
	background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
	color: #ffffff;
	box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
}

.approve-btn:not(:disabled):hover {
	box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.4);
}

.reject-btn {
	background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
	color: #ffffff;
	box-shadow: 0 4rpx 12rpx rgba(244, 67, 54, 0.3);
}

.reject-btn:not(:disabled):hover {
	box-shadow: 0 6rpx 16rpx rgba(244, 67, 54, 0.4);
}

/* 按钮加载状态 */
.action-btn:disabled::after {
	content: '';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 20rpx;
	height: 20rpx;
	border: 2rpx solid #ffffff;
	border-top: 2rpx solid transparent;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% { transform: translate(-50%, -50%) rotate(0deg); }
	100% { transform: translate(-50%, -50%) rotate(360deg); }
}

</style>
